import logging

from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.mixins import ListModelMixin, CreateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from rest_framework.viewsets import GenericViewSet, ModelViewSet, ReadOnlyModelViewSet

from shopping.models import Classification, Commodity, CommodityImg, ShoppingCart, Order
from shopping.serializers import ClassificationSerializer, ParentClassificationSerializer, CommoditySerializer, \
    ShoppingCartSerializer, OrderSerializer

from fdfs_client.client import Fdfs_client, get_tracker_conf

# 创建日志器对象
logger = logging.getLogger(__name__)
# 得到 tracker server
tracker_path = get_tracker_conf("fastdfs/client.conf")
# 创建fastdfs客户端
client = Fdfs_client(tracker_path)


# Create your views here.

# 商品分类视图集

class ClassificationViewSet(GenericViewSet, ListModelMixin):
    queryset = Classification.objects.all()
    serializer_class = ClassificationSerializer
    # 登录权限
    permission_classes = [IsAuthenticated]

    # 重写查询集方法 进行商品分层
    def get_queryset(self):
        if self.action in ['list']:
            # 查看所有商品分类 显示父级分类
            return self.queryset.filter(is_delete=False, parent__isnull=True)
        else:
            return self.queryset

    # 重写序列化器方法
    def get_serializer_class(self):
        if self.action == 'list':
            return ParentClassificationSerializer
        else:
            return self.serializer_class


    @action(methods=['get'], detail=True)
    def commodity(self,request,pk):
        try:
            classification = self.get_queryset().get(id=pk)
        except Classification.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)

        classification_attr = 'classification1'
        classification_name = classification.name
        if classification.parent:
            classification_attr = 'classification2'
            classification_name = f"{classification.parent.name}--{classification.name}"
        data = getattr(classification, classification_attr)
        commqueryset = data.filter(is_delete=False,status=1)
        return Response({
            'classification':classification_name,
            "commodity":CommoditySerializer(commqueryset, many=True).data
        })



class CommodityViewSet(ModelViewSet):
    queryset = Commodity.objects.filter(is_delete=False)
    serializer_class = CommoditySerializer
    permission_classes = [IsAuthenticated]

    # 如果是查看和查看单个商品  必须是发布的商品
    def get_queryset(self):
        if self.action in ['list', 'retrieve']:
            return self.queryset.filter(status=1)
        return self.queryset

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        # 获取用户传入的商品图片
        files = request.FILES.getlist("file")
        for file in files:
            # 判断是否是图片
            if file:
                # 是否是图片
                if file.content_type not in ("image/png", "image/jpeg", "image/gif"):
                    return Response(status=status.HTTP_400_BAD_REQUEST)
                # 获取图片后缀
                try:
                    image_ext_name = file.name.split('.')[-1]
                except Exception as e:
                    logger.info(f"图片扩展名异常{e}")
                    image_ext_name = "png"

                try:
                    upload_res = client.upload_by_buffer(file.read(), file_ext_name=image_ext_name)
                except Exception as e:
                    logger.error(f"图片上传出现未知异常")
                    return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                else:
                    if upload_res.get("Status") != "Upload successed.":
                        logger.warning("图片上传失败")
                        return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                    # 得到文件地址 进行decode解码(地址是b二进制的)
                    image_name = upload_res.get("Remote file_id").decode()

                    CommodityImg.objects.create(src=image_name, commodity_id=serializer.data["id"])
        print(1, serializer.data)
        return Response(serializer.data)

    @action(methods=['get'], detail=False)
    def optimization(self, request):
        queryset = self.get_queryset().order_by("-comments").order_by("-create_time")
        if len(queryset) >= 5:
            queryset = queryset[:5]
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

# 购物车视图集
class ShoppingCartViewSet(ModelViewSet):
    queryset = ShoppingCart.objects.all()
    serializer_class = ShoppingCartSerializer
    permission_classes = [IsAuthenticated]

    # 购物车只能看到当前用户的购物车信息
    def get_queryset(self):
        return self.request.user.shoppingcart_set.all()

    # 重写 create方法  指定登录用户的购物车
    def create(self, request, *args, **kwargs):
        request.POST._mutable = True
        request.data["user"] = str(request.user.id)
        return ModelViewSet.create(self, request, *args, **kwargs)


# 订单视图集
class OrderViewSet(ReadOnlyModelViewSet,CreateModelMixin):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer
    permission_classes = [IsAuthenticated]


    # 用户只能查看自己的订单
    def get_queryset(self):
        return  self.request.user.order_set.all()
